package com.gtp.mq.demo;

import java.io.IOException;

import org.junit.Before;

import com.rabbitmq.client.Channel;

//队列绑定
public class QueueBindFactory extends BaseFactory {

	protected Channel channel = getChannel();

	@Before
	public void initBinding() throws Exception {

		if (channel == null) {
			channel = getChannel();
		}

		// 初始化-队列绑定
		bindTopic();
		bindDirect();
		bindFanout();
	}

	// 声明exchange和queue,以及绑定关系
	private void bindTopic() throws IOException {

		// 声明转发器
		channel.exchangeDeclare("mytopicExchangeName", "topic", // type
				true);// exchange持久化durable=true

		// 绑定Key: "一个具有生成名称的非持久，独占，自动删除队列"
		// 临时队列
		// queueDeclare("", false, true, true, null);
		channel.queueDeclare("mytopicQueue1", true, false, false, null);
		channel.queueDeclare("mytopicQueue2", true, false, false, null);

		// *代表一个 #代表零个或多个
		// 绑定: 队列,topic,routingKey (routingKey指定订阅那些规则)
		channel.queueBind("mytopicQueue1", "mytopicExchangeName", "r1.*");
		channel.queueBind("mytopicQueue2", "mytopicExchangeName", "r2.*");
	}

	// 广播
	private void bindFanout() throws IOException {

		// 声明转发器
		channel.exchangeDeclare("myfanoutExchange", "fanout");

		// 声明队列
		channel.queueDeclare("myfanout_queue_1", true, false, false, null);
		channel.queueDeclare("myfanout_queue_2", true, false, false, null);

		// 绑定队列到交换器 routingKey不能为null
		channel.queueBind("myfanout_queue_1", "myfanoutExchange", "");
		channel.queueBind("myfanout_queue_2", "myfanoutExchange", "");
	}

	private void bindDirect() throws IOException {

		// 声明转发器
		channel.exchangeDeclare("mydirectExchange", "direct");

		/**
		 * 声明队列
		 * 
		 * @param queue		  队列
		 * @param durable	  是否持久队列
		 * @param exclusive	  是否独占队列(当前连接)
		 * @param autoDelete 是否自动删除(不使用时自动删除)
		 * @param arguments  队列其它属性
		 */
		channel.queueDeclare("mydirect_queue_1", true, false, false, null);

		/**
		 * 绑定队列到交换器 routingKey不能为null
		 * 
		 * @param queue
		 *            队列
		 * @param exchange
		 *            交换器
		 * @param routingKey
		 *            路由key
		 */
		channel.queueBind("mydirect_queue_1", "mydirectExchange", "r.3");
		/***********************************************************/
	}

}